package cn.play.cardgame;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;

import java.util.HashMap;
import java.util.Map;

public class DidiAudioService extends Service implements MediaPlayer.OnCompletionListener {
    public static final int PLAY_MSG = 1;
    public static final int PAUSE_MSG = 2;
    public static final int STOP_MSG = 3;
    private MediaPlayer mediaPlayer;
    // private boolean isPause; //暂停状态
    private final IBinder binder = new AudioBinder();

    private int lastSong = -1;
    // private int lastPos = 0;
    private boolean isFirst = true;

    private Map<Integer, Integer> songMap = new HashMap<Integer, Integer>();

    @Override
    public IBinder onBind(Intent arg0) {
        return binder;
    }

    /**
     * 当Audio播放完的时候触发该动作
     */
    @Override
    public void onCompletion(MediaPlayer player) {
        // stopSelf();//结束了，则结束Service
    }

    // 在这里我们需要实例化MediaPlayer对象
    public void onCreate() {
        super.onCreate();
        // 我们从raw文件夹中获取一个应用自带的mp3文件
        // mediaPlayer = MediaPlayer.create(this, R.raw.background_music);
        // mediaPlayer.setLooping(true);
        // mediaPlayer.setOnCompletionListener(this);
    }

    /**
     * 播放音乐
     *
     * @param position
     */
    private void play(int position, int song) {
        try {
//			if (mediaPlayer != null)
//				mediaPlayer.reset();// 把各项参数恢复到初始状态
            // mediaPlayer.setDataSource(path);
            // mediaPlayer.prepare(); // 进行缓冲
//			if (song == 0) {
            mediaPlayer = MediaPlayer.create(this, R.raw.didi);
            mediaPlayer.setLooping(true);
//			} else if (song == 1) {
//				mediaPlayer = MediaPlayer.create(this, R.raw.background_music);
//				mediaPlayer.setLooping(true);
//			}
            // mediaPlayer.start();
            mediaPlayer.setOnPreparedListener(new PreparedListener(position));// 注册一个监听器
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 暂停音乐
     */
    private void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            // isPause = true;
        }
    }

    /**
     * 停止音乐
     */
    private void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
//			try {
//				mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
        }
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

    /**
     * 实现一个OnPrepareLister接口,当音乐准备好的时候开始播放
     */
    private final class PreparedListener implements OnPreparedListener {
        private int positon;

        public PreparedListener(int positon) {
            this.positon = positon;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {
//			if (positon > 0) { // 如果音乐不是从头播放
//				mediaPlayer.seekTo(positon);
//			}
            mediaPlayer.start(); // 开始播放
        }
    }

    /**
     * 该方法在SDK2.0才开始有的，替代原来的onStart方法
     */
    public int onStartCommand(Intent intent, int flags, int startId) {
        // if (mediaPlayer != null && mediaPlayer.isPlaying()) {
        // stop();
        // }
        if (intent == null)
            return super.onStartCommand(intent, flags, startId);
        int msg = intent.getIntExtra("MSG", 0);
        if (msg == PLAY_MSG) {
            int currentSong = intent.getIntExtra("SONG", -1);
            if (isFirst) {
                isFirst = false;
                lastSong = currentSong;
                play(0, currentSong);
            } else {
                if (lastSong != currentSong) {
                    if (mediaPlayer != null)
                        songMap.put(lastSong, mediaPlayer.getCurrentPosition());
                    lastSong = currentSong;
                    stop();
                    // play(0, currentSong);
                    play(songMap.get(currentSong) == null ? 0 : songMap.get(currentSong), currentSong);
                } else {
                    stop();
                    play(songMap.get(currentSong) == null ? 0 : songMap.get(currentSong), currentSong);
                }
            }
        } else if (msg == PAUSE_MSG) {
            pause();
        } else if (msg == STOP_MSG) {
            stop();
        }
        return START_STICKY;
    }

    // 为了和Activity交互，我们需要定义一个Binder对象
    class AudioBinder extends Binder {

        // 返回Service对象
        DidiAudioService getService() {
            return DidiAudioService.this;
        }
    }

    // 后退播放进度
    // public void haveFun() {
    // if (player.isPlaying() && player.getCurrentPosition() > 2500) {
    // player.seekTo(player.getCurrentPosition() - 2500);
    // }
    // }
}
